import {  hashHistory } from 'dva/router';
import { message } from 'antd';
import { login } from '../services/user'

export default {
    namespace: 'user',
    state: {
        userInfo: JSON.parse(sessionStorage.getItem('user')) || {
            UserName: '未登陆',
            Roles: '',
            Token: ''
        }
    },
    effects: {
        * login({ payload }, { put, call }) {
            const data = yield call(login, payload);
            // console.log(data);
            if (data.data.Result) {
                message.success('登陆成功!' + data.data.Message)
                yield put({ type: 'loginSuccess', loginInfo: data.data });
                setTimeout(message.destroy(), 2000);
                hashHistory.push('/');
                // if(data.data.Roles.indexOf('省级客服角色') > 0){
                //   hashHistory.push('/');
                // }else{
                //   hashHistory.push('/busticket');
                // }
            } else {
                message.destroy();
                message.success('登陆失败!' + data.data.Message);
            }
        },
        * loginOut({ payload }, { put, call }) {
            // yield put({type:'loginOut'});
            // console.log('loginOut');
            // message.success('登出成功!');
            sessionStorage.removeItem('user');
            sessionStorage.removeItem('token');
            localStorage.removeItem('roles');
            hashHistory.push('/login');
            // yield put(routerRedux.push('/dashboard'));
        }
    },
    reducers: {
        loginSuccess(state, payload) {
            var userInfo = {
                UserName: payload.loginInfo.UserName,
                Roles: payload.loginInfo.Roles,
                Token: payload.loginInfo.Token
            };
            localStorage.setItem('roles', JSON.stringify(userInfo.Roles));
            sessionStorage.setItem('user', JSON.stringify(userInfo));
            sessionStorage.setItem('token', userInfo.Token);
            // console.log('loginSuccess');
            // console.log(userInfo);
            // console.log(JSON.parse(localStorage.getItem('user')));
            return {
                ...state,
                userInfo: userInfo
            }
        },

    }
}
